import { login, register, logout, fetchUser } from '@/api/auth'

const state = {
  user: null,
  token: localStorage.getItem('token') || null,
  loading: false,
  error: null
}

const getters = {
  isAuthenticated: (state) => !!state.token,
  currentUser: (state) => state.user
}

const mutations = {
  SET_USER(state, user) {
    state.user = user
  },
  SET_TOKEN(state, token) {
    state.token = token
    localStorage.setItem('token', token)
  },
  CLEAR_USER(state) {
    state.user = null
  },
  CLEAR_TOKEN(state) {
    state.token = null
    localStorage.removeItem('token')
  },
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  SET_ERROR(state, error) {
    state.error = error
  }
}

const actions = {
  async login({ commit }, credentials) {
    commit('SET_LOADING', true)
    commit('SET_ERROR', null)
    
    try {
      const { token, user } = await login(credentials)
      commit('SET_TOKEN', token)
      commit('SET_USER', user)
      return user
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async register({ commit }, userData) {
    commit('SET_LOADING', true)
    commit('SET_ERROR', null)
    
    try {
      const { token, user } = await register(userData)
      commit('SET_TOKEN', token)
      commit('SET_USER', user)
      return user
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async logout({ commit }) {
    try {
      await logout()
      commit('CLEAR_USER')
      commit('CLEAR_TOKEN')
    } catch (error) {
      console.error('Logout error:', error)
      commit('CLEAR_USER')
      commit('CLEAR_TOKEN')
    }
  },
  
  async fetchUser({ commit }) {
    commit('SET_LOADING', true)
    
    try {
      const user = await fetchUser()
      commit('SET_USER', user)
      return user
    } catch (error) {
      console.error('Fetch user error:', error)
      commit('CLEAR_USER')
      commit('CLEAR_TOKEN')
      return null
    } finally {
      commit('SET_LOADING', false)
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}